﻿using System.Data.Entity;
using System.Web.Mvc;
using System.Web.Routing;

using Appetite.Development;
using Nais.Presentation.Web.Mvc;

namespace Appetite.Presentation.Web
{
    public class MvcApplication : System.Web.HttpApplication
    {
        public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {
            filters.Add(new HandleErrorAttribute());
        }

        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                "Default", // Route name
                "{controller}/{action}/{id}", // URL with parameters
                new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
            );

            routes.MapRoute("OpenIdDiscover", "Auth/Discover");
        }

        protected void Application_Start()
        {
            Bootstrapper.Initialise();

            #if DEBUG
                Database.SetInitializer(new AppetiteDbInitializer());
            #endif

            AreaRegistration.RegisterAllAreas();
            RegisterGlobalFilters(GlobalFilters.Filters);
            RegisterRoutes(RouteTable.Routes);
            AddPluggableConventions();
        }

        private static void AddPluggableConventions()
        {
            ModelMetadataProvider current = ModelMetadataProviders.Current;
            var conventionsProvider = new PluggableConventionsModelMetadataProvider(current);
            conventionsProvider.AddConvention(m =>
            {
                if (m.PropertyName == "Id" ||
                    m.PropertyName == "CreationDate" ||
                    m.PropertyName == "ModificationDate")
                {
                    m.TemplateHint = "HiddenInput";
                    m.HideSurroundingHtml = true;
                }
            });

            ModelMetadataProviders.Current = conventionsProvider;
        }
    }
}